<template>
  <el-dialog title="权限设置" width="600px" v-model="dialogVisible">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>页面权限</span>
        </div>
      </template>
      <el-tree
        ref="treeRef"
        show-checkbox
        :data="formatTreeData(menu)"
        node-key="url"
      />
    </el-card>
    <el-card class="mt">
      <template #header>
        <div class="card-header">
          <span>按钮权限</span>
        </div>
      </template>
      <el-checkbox-group v-model="initBtnAuth">
        <el-checkbox label="全部" value="all" />
        <el-checkbox label="添加" value="add" />
        <el-checkbox label="编辑" value="edit" />
        <el-checkbox label="删除" value="delete" />

       
      </el-checkbox-group>
    </el-card>
    <template #footer>
      <el-button  @click="setVisible">取消</el-button>
      <el-button type="primary" @click="handleSave">确认</el-button>

    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { useUserStore } from '@/store/auth';
import { storeToRefs } from 'pinia';
import { setAuthApi } from '@/api/system';
import { ElMessage } from 'element-plus';
const props = defineProps({
  currentRoleList: Array,
  currentBtnAuth: Array,
  currentAccount: String,
});
const dialogVisible = ref(false);
const userStore = useUserStore();
const { menu } = storeToRefs(userStore);
const emit = defineEmits(['reload']);

const formatTreeData = (data: any) => {
  return data.map((item: any) => {
    let newNode: any = {
      label: item.name,
      url: item.url,
    };
    if (item.children) {
      newNode.children = formatTreeData(item.children);
    }
    return newNode;
  });
};
const treeRef = ref<any>();

const initBtnAuth = ref<any[]>([]);

// 对话框显示时需等待DOM更新后设置选中项
const setVisible = () => {
  dialogVisible.value = !dialogVisible.value;
};
// 需添加deep监听确保数组内容变化可捕获
watch(
  () => props.currentRoleList,
  () => {
    treeRef.value?.setCheckedKeys(props.currentRoleList || []);
  },
  { deep: true }
); // 增加deep配置

watch(
  () => props.currentBtnAuth,
  () => {
    initBtnAuth.value = props.currentBtnAuth || [];
  },
  { deep: true }
);

const handleSave = async () => {
    const obj = {
    account: props.currentAccount,
    pageList: treeRef.value?.getCheckedKeys(true), // 传入true可以过滤掉父节点 , 只返回子节点
    btnList: initBtnAuth.value,
  }
    console.log("👿 ~ handleSave ~ obj:", obj)
  const res = await setAuthApi(obj);
  if(res.code === 200){
    ElMessage.success("操作成功")
    setVisible()
    emit('reload')
  }
  
};

defineExpose({
  setVisible,
});
</script>
